package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImp extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;


    /**
     * 根据id来删除菜品分类(看是否有关联菜品和套餐 无则删除有则删除不了)
     *
     * @param id
     */
    @Override
    public void remove(Long id) {
        //查询当前分类是否关联了菜品，如果关联则抛出业务异常
        LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<>();
        dishQueryWrapper.eq(Dish::getCategoryId, id);  //id是当前分类管理的id
        int count = dishService.count(dishQueryWrapper);
         if (count > 0) {
             //已经关联了菜品，抛出业务异常
             throw new CustomException("当前类别下关联了菜品，无法删除！");
         }
        // 查询当前分类是否关联了套餐，如果关联则抛出业务异常
        LambdaQueryWrapper<Setmeal> setmealQueryWrapper = new LambdaQueryWrapper<>();
         setmealQueryWrapper.eq(Setmeal ::getCategoryId,id);
        int count1 = setmealService.count(setmealQueryWrapper);
        if (count1 > 0) {
            //已关联了套餐，抛出业务异常
            throw new CustomException("当前类别下关联了套餐，无法删除！");
        }

        //正常删除分类
        //1、当子类与父类有同名的属性时，可以通过super。属性的方式调用父类中生命的属性。
        //2、当子类重写父类的方法后，在子类中若想调用父类中被重写的方法时，需用super.的方法
        super.removeById(id);
    }
}
